#include "head.h"
int sendfd(int sockfd, int fdtosend, int exitFlag){
    struct msghdr hdr;
    bzero(&hdr,sizeof(hdr)); // 把name部分置空，不能省略
    // 消息正文
    struct iovec iov[1];
    iov[0].iov_base = &exitFlag;
    iov[0].iov_len = sizeof(int);
    hdr.msg_iov = iov;
    hdr.msg_iovlen = 1;
    // 控制信息字段 data要存入一个文件描述符int
    // 因为cmsghdr是变长数组，所以只能申请在堆上
    struct cmsghdr *pcmsg = (struct cmsghdr *)calloc(1,CMSG_LEN(sizeof(int))); 
    pcmsg->cmsg_len = CMSG_LEN(sizeof(int));
    pcmsg->cmsg_level = SOL_SOCKET;
    pcmsg->cmsg_type = SCM_RIGHTS;//说明传递的是文件描述符
    // 先找到data的首地址，把fdtosend填入
    *(int *)CMSG_DATA(pcmsg) = fdtosend; // 首地址强转成int *，再解引用
    hdr.msg_control = pcmsg;//hdr管理消息的控制信息字段
    hdr.msg_controllen = CMSG_LEN(sizeof(int));
    // 调用sendmsg函数
    int ret = sendmsg(sockfd,&hdr,0);
    ERROR_CHECK(ret,-1,"sendmsg");
    return 0;
}
int recvfd(int sockfd, int *pfdtorecv, int *pexitFlag){
    struct msghdr hdr;
    bzero(&hdr,sizeof(hdr)); // 把name部分置空，不能省略
    // 消息正文
    struct iovec iov[1];
    iov[0].iov_base = pexitFlag;
    iov[0].iov_len = sizeof(int);
    hdr.msg_iov = iov;
    hdr.msg_iovlen = 1;
    // 控制信息字段 data要存入一个文件描述符int
    // 因为cmsghdr是变长数组，所以只能申请在堆上
    struct cmsghdr *pcmsg = (struct cmsghdr *)calloc(1,CMSG_LEN(sizeof(int))); 
    pcmsg->cmsg_len = CMSG_LEN(sizeof(int));
    pcmsg->cmsg_level = SOL_SOCKET;
    pcmsg->cmsg_type = SCM_RIGHTS;//说明传递的是文件描述符
    hdr.msg_control = pcmsg;//hdr管理消息的控制信息字段
    hdr.msg_controllen = CMSG_LEN(sizeof(int));
    // 调用recvmsg函数
    int ret = recvmsg(sockfd,&hdr,0);
    ERROR_CHECK(ret,-1,"recvmsg");
//    printf("buf1 = %s, buf2 = %s\n", buf1,buf2);
    *pfdtorecv = *(int *)CMSG_DATA(pcmsg);
    return 0;
}
